class Category {
    constructor() {
        this.container = document.getElementById('categoryList');
        this.init();
    }

    async init() {
        try {
            const data = await fetchData(API.CATEGORY.LIST);
            this.render(data);
            this.bindEvents();
        } catch (error) {
            Alert.show(`分类加载失败: ${error.message}`, 'error');
        }
    }

    render(categories) {
        this.container.innerHTML = categories.map(cat => `
                <div class="category-item" 
                     data-id="${cat.categoryId}"
                     data-name="${cat.categoryName}">
                    ${cat.categoryName}
                </div>
            `).join('');
    }

    bindEvents() {
        this.container.addEventListener('click', (e) => {
            const target = e.target.closest('.category-item');
            if (!target) return;

            this.toggleActive(target);
            this.emitCategoryChange(target);
        });
    }

    toggleActive(target) {
        document.querySelectorAll('.category-item').forEach(item => {
            item.classList.remove('active');
        });
        target.classList.add('active');
    }

    emitCategoryChange(target) {
        const event = new CustomEvent('categoryChanged', {
            detail: {
                categoryId: target.dataset.id,
                categoryName: target.dataset.name
            }
        });
        window.dispatchEvent(event);
    }
}

// 初始化分类模块
document.addEventListener('DOMContentLoaded', () => {
    new Category();
});